package com.jl.thread.waitnotify;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用Lock condition实现线程等待唤醒机制
 */
public class LockAwaitSigalDemo {


    public static void main(String[] args) {

        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        new Thread(()->{

            try{
                lock.lock();
                System.out.println(Thread.currentThread().getName() + "来了");

                //await必须在lock代码块里
                condition.await();

                System.out.println(Thread.currentThread().getName() + "又来了");

            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }).start();


        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        try{

            lock.lock();
            System.out.println(Thread.currentThread().getName() + "来了啊啊啊啊");

            //唤醒
            condition.signal();

            System.out.println(Thread.currentThread().getName() + "还来了啊啊啊啊");

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }



    }



}
